import {Component, OnInit, ViewChild} from '@angular/core';
import {MatDialog, MatPaginator, MatSnackBar, MatSort, MatTableDataSource} from '@angular/material';
import {Customer} from '../shared/customer.model';
import {CustomerService} from '../shared/customer.service';
import {Router} from '@angular/router';
import {ConfirmDialogComponent} from '../../core/confirm-dialog/confirm-dialog.component';

@Component({
  selector: 'app-customer-list',
  templateUrl: './customer-list.component.html',
  styleUrls: ['./customer-list.component.css']
})
export class CustomerListComponent implements OnInit {
  displayedColumns = ['detail', 'id', 'name', 'gender', 'mobile', 'membership', 'credit', 'oper'];
  dataSource: MatTableDataSource<Customer>;
  customers: Customer[] = [];

  inputValueUserMobileFilter: string;
  inputValueUserNameFilter: string;

  @ViewChild(MatPaginator) paginator: MatPaginator;
  @ViewChild(MatSort) sort: MatSort;

  constructor(private customerService: CustomerService,
              private router: Router,
              private snackBar: MatSnackBar,
              private dialog: MatDialog) {
  }

  ngOnInit() {
    this.loadCustomerList();
  }

  loadCustomerList() {
    this.customerService.getCustomerList().subscribe( (value) => {
      this.customers = <Customer[]><any>value;
      this.dataSource = new MatTableDataSource<Customer>(this.customers);
      this.refreshTable();
      this.dataSource.paginator = this.paginator;
      this.dataSource.sort = this.sort;
    });
  }

  onAddClick(target) {
    this.router.navigate(['customers/', -1]); // -1 means new washer.
  }
  selectRow(target, row) {
    this.customerService.currentCustomer = row;
    this.router.navigate(['customers/', row.id]);
  }
  onDeleteClicked(target, row) {
    const dialogRef = this.dialog.open(ConfirmDialogComponent);
    dialogRef.afterClosed().subscribe( result => {
      if (result) {
        this.customerService.currentCustomer = row;
        const customerId = this.customerService.currentCustomer.id;
        this.customerService.deleteCustomer(String(customerId)).subscribe( value => {
          if (value) {
            const index = this.customers.findIndex( elem => elem.id === customerId);
            this.dataSource.data.splice(index, 1);
            this.refreshTable();
            this.openSnackBar('客户已删除！', '');
          } else {
            this.openSnackBar('删除客户失败！', '');
          }
        });
      }
    });
  }
  applyUserNameFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filterPredicate = (data: Customer, filter: string) => String((data.lastName + data.firstName)).indexOf(filterValue) !== -1;
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.clearFilters('userNameFilter');
  }
  applyUserMobileFilter(filterValue: string) {
    filterValue = filterValue.trim();
    filterValue = filterValue.toLowerCase();
    this.dataSource.filterPredicate = (data: Customer, filter: string) => data.phoneNumber.indexOf(filterValue) !== -1;
    this.dataSource.filter = filterValue;
    if (this.dataSource.paginator) {
      this.dataSource.paginator.firstPage();
    }
    this.clearFilters('userMobileFilter');
  }
  clearFilters(filterName: string) {
    if (filterName === 'userNameFilter') {
      this.inputValueUserMobileFilter = '';
    }
    if (filterName === 'userMobileFilter') {
      this.inputValueUserNameFilter = '';
    }
  }
  private refreshTable() {
    this.dataSource.filter = '1';
    this.dataSource.filter = '';
  }
  openSnackBar(message: string, action: string) {
    this.snackBar.open(message, action, {
      duration: 2000
    });
  }
}
